const {app, BrowserWindow} = require('electron')
const remote = require('@electron/remote/main')
remote.initialize()

const path = require('path')
const isDev = process.env.VITE_NODE_ENV === 'development'
const EventEmitter = require('events')

// 初始化全局事件发射器
global.eventEmitter = new EventEmitter()

function createWindow() {
    const mainWindow = new BrowserWindow({
        width: 1320,
        height: 768,
        title: process.env.VITE_APP_TITLE || '凯昇上位机',
        autoHideMenuBar: true,
        resizable: true,  // 修改为 true，允许调整窗口大小
        maximizable: true, // 明确允许最大化
        show: false, // 先不显示窗口
        webPreferences: {
            backgroundThrottling: false, // 禁用后台节流
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true,
            sandbox: false,
            webSecurity: false
        }
    })
    // 启用 @electron/remote
    remote.enable(mainWindow.webContents);
    
    // 窗口准备就绪后最大化并显示
    mainWindow.once('ready-to-show', () => {
        mainWindow.maximize()
        mainWindow.show()
    })

    // 加载应用
    if (isDev) {
        console.log('加载开发环境')
        mainWindow.loadURL('http://localhost:5173')
        mainWindow.webContents.openDevTools()
    } else {
        // 拆解路径并打印
        const distPath = path.join(__dirname, '../dist')
        const indexPath = path.join(distPath, 'index.html')

        console.log('当前目录 (__dirname):', __dirname)
        console.log('dist 目录路径:', distPath)
        console.log('index.html 完整路径:', indexPath)

        // 检查文件是否存在
        const fs = require('fs')
        if (fs.existsSync(indexPath)) {
            console.log('index.html 文件存在')
            mainWindow.loadFile(indexPath)
        } else {
            console.error('错误: index.html 文件不存在')
            console.log('请检查是否已执行 npm run build')
        }
    }
    return mainWindow
}

app.whenReady().then(async () => {
    try {
        createWindow()
    } catch (error) {
        console.error('应用程序初始化失败:', error)
    }
})

app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
